package com.aijle.videopaper.activity;

import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Switch;

import com.aijle.videopaper.R;
import com.aijle.videopaper.receiver.OverlayReceiver;
import com.aijle.videopaper.service.OverlayService;
import com.aijle.videopaper.service.VideoWallpaperService;
import com.aijle.videopaper.util.ActivityUtil;
import com.aijle.videopaper.util.IOverlay;
import com.aijle.videopaper.util.OverlayHelper;
import com.aijle.videopaper.util.PermissionCheck;
import com.aijle.videopaper.util.Preferences;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.dync.ijkplayerlib.widget.util.Settings;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

import static com.aijle.videopaper.receiver.OverlayReceiver.HIDEDESKTOP;
import static com.aijle.videopaper.receiver.OverlayReceiver.PLAYNEXT;
import static com.aijle.videopaper.receiver.OverlayReceiver.RELOAD;
import static com.aijle.videopaper.receiver.OverlayReceiver.SHOWDESKTOP;
import static com.aijle.videopaper.receiver.OverlayReceiver.UPDATESENSOR;
import static com.aijle.videopaper.receiver.OverlayReceiver.UPDATETYPE;
import static com.aijle.videopaper.receiver.OverlayReceiver.UPDATEVOLUME;
import static com.aijle.videopaper.receiver.OverlayReceiver.UPDATEXPOS;

public class MainActivity extends AppCompatActivity implements IOverlay {
    Preferences mPreferences;
    private OverlayReceiver mReceiver;
    List<String> mVideoList;

    @BindView(R.id.mute)
    Switch mute;

    @BindView(R.id.autoOpen)
    Switch autoOpen;

    @BindView(R.id.showDesktop)
    Switch showDesktop;

    @BindView(R.id.random)
    Switch random;

    @BindView(R.id.chooseVideo)
    Button chooseVideo;

    @BindView(R.id.floatWindow)
    Button floatWindow;

    @BindView(R.id.notification)
    Button notification;

    @BindView(R.id.usage)
    Button usage;

    @BindView(R.id.volume)
    SeekBar volume;

    @BindView(R.id.opacity)
    SeekBar opacity;

    @BindView(R.id.xpos)
    SeekBar xpos;

    @BindView(R.id.sensor)
    Switch sensor;

    @BindView(R.id.curActivity)
    Button curActivity;

    @BindView(R.id.power)
    Button power;

    @OnCheckedChanged(R.id.sensor)
    void onSensor(boolean checked) {
        mPreferences.setSensor(checked);
        xpos.setEnabled(!checked);
        updateOverlay(UPDATESENSOR);
    }
//    @BindView(R.id.accessibility)
//    Button accessibility;

    @OnCheckedChanged(R.id.autoOpen)
    void onAutoOpen(boolean checked) {
        mPreferences.setAutoOpen(checked);
        updateOverlay(RELOAD);
    }

    @OnCheckedChanged(R.id.showDesktop)
    void onShowDesktop(boolean checked) {
        mPreferences.setShowDesktop(checked);
        updateOverlay(RELOAD);
//        if (checked) {
//            updateOverlay(SHOWDESKTOP);
//        } else {
//            updateOverlay(HIDEDESKTOP);
//        }
    }

    @OnCheckedChanged(R.id.mute)
    void onMute(boolean checked) {
        mPreferences.setMute(checked);
        updateOverlay(UPDATEVOLUME);
    }

    @OnCheckedChanged(R.id.random)
    void onRandom(boolean checked){
        mPreferences.setRandom(checked);
        updateOverlay(RELOAD);
    }

    @OnClick(R.id.floatWindow)
    void onFloatWindow(){
        ActivityUtil.turnToOverlayPermission(this);
    }

    @OnClick(R.id.notification)
    void onNotification() {
        ActivityUtil.turnToNotifyPermission(this);
    }

    @OnClick(R.id.curActivity)
    void onCurActivity() {
        Intent intent = new Intent(android.provider.Settings.ACTION_USAGE_ACCESS_SETTINGS);
        startActivity(intent);
    }

    @OnClick(R.id.power)
    void onPower() {
        Intent intent = new Intent(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        intent.setData(Uri.parse("package:" + this.getPackageName()));
        startActivity(intent);
    }

    @OnClick(R.id.playNext)
    void onPlayNext() {
        updateOverlay(PLAYNEXT);
    }

    @OnClick(R.id.usage)
    void onUsage() {
        startActivity(new Intent(android.provider.Settings.ACTION_USAGE_ACCESS_SETTINGS));
    }

    @OnClick(R.id.chooseVideo)
    void onChooseVideo() {
        PictureSelector.create(MainActivity.this)
                .openGallery(PictureMimeType.ofVideo())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
//                .theme()//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                .maxSelectNum(100)// 最大图片选择数量 int
                .maxVideoSelectNum(100)
//                .minSelectNum()// 最小选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(false)// 是否可预览图片 true or false
                .previewVideo(true)// 是否可预览视频 true or false
                .enablePreviewAudio(false) // 是否可播放音频 true or false
                .isCamera(false)// 是否显示拍照按钮 true or false
//                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
//                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
//                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
//                .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
//                .enableCrop(false)// 是否裁剪 true or false
//                .compress(false)// 是否压缩 true or false
//                .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                .withAspectRatio()// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//                .hideBottomControls()// 是否显示uCrop工具栏，默认不显示 true or false
//                .isGif()// 是否显示gif图片 true or false
//                .compressSavePath(getPath())//压缩图片保存地址
//                .freeStyleCropEnabled()// 裁剪框是否可拖拽 true or false
//                .circleDimmedLayer()// 是否圆形裁剪 true or false
//                .showCropFrame()// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
//                .showCropGrid()// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
//                .openClickSound()// 是否开启点击声音 true or false
//                .selectionMedia()// 是否传入已选图片 List<LocalMedia> list
//                .previewEggs()// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
//                .cropCompressQuality()// 裁剪压缩质量 默认90 int
//                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
//                .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
//                .rotateEnabled() // 裁剪是否可旋转图片 true or false
//                .scaleEnabled()// 裁剪是否可放大缩小图片 true or false
//                .videoQuality()// 视频录制质量 0 or 1 int
//                .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
//                .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
//                .recordVideoSecond()//视频秒数录制 默认60s int
//                .isDragFrame(false)// 是否可拖动裁剪框(固定)
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    void updateOverlay(int updateType) {
        Intent intent = new Intent(OverlayReceiver.UPDATE_ACTION);
        intent.putExtra(UPDATETYPE, updateType);
        sendBroadcast(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    mVideoList = new ArrayList<>();
                    for (LocalMedia s : selectList) {
                        mVideoList.add(s.getPath());
                    }
                    mPreferences.setVideoList(mVideoList);
                    updateOverlay(OverlayReceiver.RELOAD);
                    break;
            }
        }
    }

    Settings mSetting;
    OverlayHelper mOverlayHelper;
    boolean useService = true;

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
            mReceiver = null;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

//        {
//            Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
//            intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(this, VideoWallpaperService.class));
//            startActivity(intent);
//        }
//        if (useService) {
            Intent intent = new Intent(this, OverlayService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                this.startForegroundService(intent);
            } else {
                this.startService(intent);
            }
//        } else {
//            mOverlayHelper = new OverlayHelper(this);
//            mReceiver = new OverlayReceiver();
//            IntentFilter intentFilter = new IntentFilter();
//            intentFilter.addAction(OverlayReceiver.SWITCH_ACTION);
//            intentFilter.addAction(OverlayReceiver.UPDATE_ACTION);
//            intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
//            intentFilter.addAction(Intent.ACTION_SCREEN_ON);
//            registerReceiver(mReceiver, intentFilter);
//        }

        mSetting = new Settings(this);
        mSetting.setEnableSurfaceView(false);
        mSetting.setEnableTextureView(true);

        mPreferences = new Preferences(this);

        updateUi2();

        SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                mPreferences.setVolume(i);
                updateOverlay(UPDATEVOLUME);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        };
        volume.setOnSeekBarChangeListener(seekBarChangeListener);

        SeekBar.OnSeekBarChangeListener seekBarChangeListener2 = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                mPreferences.setOpacity(i);
                updateOverlay(OverlayReceiver.UPDATELAYOUT);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        };
        opacity.setOnSeekBarChangeListener(seekBarChangeListener2);

        SeekBar.OnSeekBarChangeListener seekBarChangeListener3 = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                mPreferences.setVideoXPos(i);
                updateOverlay(UPDATEXPOS);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        };
        xpos.setOnSeekBarChangeListener(seekBarChangeListener3);
    }


    @Override
    protected void onResume() {
        super.onResume();

        updateUi();
    }

    void updateUi2() {
        autoOpen.setChecked(mPreferences.getAutoOpen());
        mute.setChecked(mPreferences.getMute());
        random.setChecked(mPreferences.getRandom());
        volume.setProgress(mPreferences.getVolume());
        opacity.setMax(80);
        opacity.setProgress(mPreferences.getOpacity());
        sensor.setChecked(mPreferences.getSensor());
        xpos.setProgress(mPreferences.getVideoXPos());
        xpos.setEnabled(!mPreferences.getSensor());
        showDesktop.setChecked(mPreferences.getShowDesktop());
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    boolean hasUsageStatsPermission(Context context) {
        AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        int mode = appOps.checkOpNoThrow("android:get_usage_stats",
                android.os.Process.myUid(), context.getPackageName());
        boolean granted = mode == AppOpsManager.MODE_ALLOWED;
        return granted;
    }

    void updateUi() {
        updateUi2();

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            floatWindow.setVisibility(View.GONE);
        } else if (!PermissionCheck.hasOverlayPermission(this)) {
            floatWindow.setVisibility(View.VISIBLE);

//            CustomDialog.showInstance(
//                    this,
//                    "需要开启【悬浮窗权限】",
//                    "取消",
//                    new CustomDialog.CancleCallback() {
//                        @Override
//                        public void onCancle() {
//
//                        }
//                    },
//                    "去开启",
//                    new CustomDialog.ConfirmCallback() {
//                        @Override
//                        public void onConfirm() {
//                            MainActivity.this.onFloatWindow();
//                        }
//                    });
        } else {
            floatWindow.setVisibility(View.GONE);
        }

//        if (PermissionCheck.getForegroundProcess(this) == null) {
//            curActivity.setVisibility(View.VISIBLE);
//        } else {
            curActivity.setVisibility(View.GONE);
//        }
        // 设置"通知权限"显示样式（4.4以下默认不需要请求该权限）
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            notification.setVisibility(View.GONE);
        } else if (!PermissionCheck.hasNotifyPermission(this)){
            notification.setVisibility(View.VISIBLE);

//            CustomDialog.showInstance(
//                    this,
//                    "需要开启【通知权限】",
//                    "取消",
//                    new CustomDialog.CancleCallback() {
//                        @Override
//                        public void onCancle() {
//
//                        }
//                    },
//                    "去开启",
//                    new CustomDialog.ConfirmCallback() {
//                        @Override
//                        public void onConfirm() {
//                            MainActivity.this.onNotification();
//                        }
//                    });
        } else {
            notification.setVisibility(View.GONE);
        }

        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);

        boolean hasIgnored = false;
        power.setVisibility(View.GONE);
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
//            hasIgnored = powerManager.isIgnoringBatteryOptimizations(this.getPackageName());
//            //  判断当前APP是否有加入电池优化的白名单，如果没有，弹出加入电池优化的白名单的设置对话框。
//            if(!hasIgnored) {
//                power.setVisibility(View.VISIBLE);
//            }
//        }

        if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
                && !hasUsageStatsPermission(this)) {
            usage.setVisibility(View.VISIBLE);
        } else {
            usage.setVisibility(View.GONE);
        }
    }

    @Override
    public void playNext() {
        mOverlayHelper.playNext();
    }

    @Override
    public void reload() {
        mOverlayHelper.reload();
    }

    @Override
    public void toggle() {
        mOverlayHelper.toggle();
    }

    @Override
    public void open() {
        mOverlayHelper.open();
    }

    @Override
    public void close() {
        mOverlayHelper.close();
    }

    @Override
    public void updateLayout() {
        mOverlayHelper.updateLayout();
    }

    @Override
    public void switchSound() {
        mOverlayHelper.switchSound();
    }

    @Override
    public void updateVolume() {
        mOverlayHelper.updateVolume();
    }

    @Override
    public void updateXPos() {
        mOverlayHelper.updateXPos();
    }

    @Override
    public void updateSensor(boolean stop) {
        updateSensor(stop, true);
    }

    public void updateSensor(boolean stop, boolean resetx) {
        mOverlayHelper.updateSensor(stop, resetx);
    }

    @Override
    public void pause() {
        mOverlayHelper.pause();
    }

    @Override
    public void resume() {
        mOverlayHelper.resume();
    }
}
